<template>
    <div class="loan-iou-add">
        <div class="wrapper">
            <p class='explain'>借条生成后，可前往<span class='orange'> “我的账户” </span>进行查看。</p>
            <ul class="form-box">
                <li class="form__item select">
                    <span class="form__key">我是</span>
                    <div class="form__value">
                        <picker-list key='loanType' picker-id='loanType' :list='loanTypeList' v-model='loanType'></picker-list>
                    </div>
                </li>
            </ul>
            <ul class="form-box">
                <li class="form__item disabled" v-if='loanType != -1'>
                    <span class="form__key">{{nameKeyMe}}</span>
                    <div class="form__value">
                        <span class='item'>{{(userInfo.user && userInfo.user.realName) || placeholder}}</span>
                    </div>
                </li>
                <li class="form__item" v-if='loanType != -1'>
                    <span class="form__key">{{nameKey}}</span>
                    <div class="form__value">
                        <input v-model='name' type="text" placeholder="请输入对方真实姓名">
                    </div>
                </li>
                <li class="form__item">
                    <span class="form__key">借款金额</span>
                    <div class="form__value">
                        <input @keyup='setMax' v-model='amount' type="tel" placeholder="请输入整数 (元)">
                    </div>
                </li>
            </ul>
            <!-- 我的借条 -->
            <h1 class="explain">您当前的可借额度为<span class='orange'>{{quota | toYuan('format')}}</span>元</h1>
            
            <ul class="form-box">
                <li class="form__item detail select">
                    <span class="form__key">借款日期</span>
                    <div class="form__value">
                        <picker-date key='borrowDate' picker-id='borrowDate' v-model='borrowDate'></picker-date>
                    </div>
                </li>
                <li class="form__item detail select">
                    <span class="form__key">还款日期</span>
                    <div class="form__value">
                        <picker-date key='repayDate' picker-id='repayDate' v-model='repayDate'></picker-date>
                    </div>
                    <p class='real-days' v-show='realDays'>{{realDays}}天</p>
                </li>
                <li class="form__item detail select">
                    <span class="form__key">年化利率</span>
                    <div class="form__value">
                        <picker-list picker-id='yearRate' :list='yearRateList' v-model='yearRate'>
                            <!-- <p>{{calcObject.interestAmount | toYuan}}</p> -->
                        </picker-list>
                    </div>
                </li>
                <li class="form__item detail disabled">
                    <span class="form__key">还款方式</span>
                    <div class="form__value"><p class='item'> 还本付息 </p></div>
                </li>
            </ul>

            <ul class="form-box" v-if='usageList.length'>
                <li class="form__item detail select">
                    <span class="form__key">借款用途</span>
                    <div class="form__value">
                        <picker-list picker-id='usage' :list='usageList' v-model='usage'>
                            <!-- <p>{{calcObject.interestAmount | toYuan}}</p> -->
                        </picker-list>
                    </div>
                </li>
            </ul>
            
            <div class="form__agreement">
                <check-box v-model='agreementCheck'><span class='form__agreement-text'>已阅读并同意 <em @click.stop='showAgreement = true'>《有借借款协议》</em> </span></check-box>
            </div>
            <div class="tips">
                <p>提示</p>
                <p>1、补借条不享受服务费和逾期管理费的奖励，不能走线上还款、不提供逾期催收工具，存在非常大的风险，请谨慎使用。</p>
                <p>2、如果您是现金交易请不要补借条，一旦发生争议，因此双方无法提供交易证据，平台会将借条设置为有争议状态。</p>
                <p>3、补借条的待确认有效期为3天，到期自动关闭。</p>
                <p>4、补借条不支持线上出借，请确保你们已经线下交易完毕。</p>
            </div>
        </div>
        <div class="single-button">
            <span class="button" @click='confirm' :class='{disabled : !agreementCheck}'>生成借条</span>
        </div>

        <login
            :show='showLogin'
            @finish='getQuota'
            @close='showLogin = false'></login>
        
        <auth-step
            v-if='noAuth'
            action='back'
            mode='bank'
            :show='showTips'
            @toggle='showTips = !showTips'
            @close='showTips = false'>
        </auth-step>

        <modal
            :show='showServiceTips'
            @close='showServiceTips = false'>
            <div class="modal-tips">
                <p>服务费是什么？ </p>
                <p>服务费最高不超过借款金额12%，由借款人自行设置，平台在交易成功后自动扣取。</p> 
            </div>
        </modal>

        <pay-password
            v-if='userInfo.user'
            :show='showPayPassword'
            @close='showPayPassword=false'
            @finish='payFinish'></pay-password>

        <agreement
            :show='showAgreement'
            @close='showAgreement=false'></agreement>
    </div>
</template>

<script>
    import { Promise } from 'es6-promise'
    import footerBar from '../components/FooterBar.vue'
    import selectGroup from '../components/SelectGroup.vue'
    import selectOption from '../components/SelectOption.vue'
    import radioGroup from '../components/RadioGroup.vue'
    import areaSelect from '../components/AreaSelect.vue'
    import radio from '../components/Radio.vue'
    import loading from '../components/Loading.vue'
    import checkBox from '../components/CheckBox.vue'
    import toolTip from '../components/ToolTip.vue'
    import modal from '../components/Modal.vue'
    import confirm from '../components/Confirm.vue'
    import buttonLoading from '../components/ButtonLoading.vue'
    import authStep from '../components/AuthStep.vue'
    import pagination from '../components/Pagination.vue'
    import payPassword from '../components/PayPassword.vue'
    import agreement from '../components/Agreement.vue'
    import verificationCode from '../components/VerificationCode.vue'
    import pickerList from '../components/PickerList.vue'
    import pickerDate from '../components/PickerDate.vue'
    import toYuan from '../filters/filter-toYuan'
    import dateFormat from '../filters/filter-dateFormat'
    import yearRateList from '../data/yearRateList'
    import paywayList from '../data/paywayList'
    import daysList from '../data/daysList'
    import periodsList from '../data/periodsList'
    import { rules } from '../utils/utils'
    import login from '../components/Login.vue'
    import  { mapGetters, mapActions }  from 'vuex'
    import { LoanIOUAddValidation } from '../validation/validation'
    import { receiptApi, loanInApi, loanOutApi, userApi } from '../api/api'
    import moment from 'moment'

    export default {
        components:{
            footerBar,
            authStep,
            selectGroup,
            selectOption,
            radioGroup,
            radio,
            login,
            checkBox,
            areaSelect,
            loading,
            toolTip,
            modal,
            confirm,
            agreement,
            buttonLoading,
            pagination,
            payPassword,
            verificationCode,
            pickerList,
            pickerDate
        },
        filters:{
            toYuan,
            dateFormat,
        },
        data() {
            return {
                number:this.$route.params.number,
                placeholder:'--',
                showTips:false,
                showServiceTips:false,
                showLogin:false,
                usageList:[],
                usage:-1,
                name:'',
                amount:'',
                days:'',
                borrowDate:'',
                repayDate:'',
                daysList:daysList,
                periods:'',
                periodsList:periodsList,
                quota:'',
                detail:{},
                calcObject:{},
                showPayPassword:false,
                showAgreement:false,
                buttonText:'',
                main:{},
                password:'',
                payway:'HBFX',
                paywayList:paywayList,
                isPublics:[{
                    value:1,
                    display:'是'
                },{
                    value:0,
                    display:'否'
                }],
                isPublic:1,
                loanTypeList:[{
                    value:'borrow',
                    display:'借款人'
                },{
                    value:'lend',
                    display:'出借人'
                }],
                loanType:-1,
                yearRate:-1,
                yearRateList:yearRateList,
                serviceFee:'',
                agreementCheck:true,
                payPasswordShow:false,
                payStatus:'',
                userCount:'',
                listInfo:{},
                records:[],
                loading:true,
                loading_calc:false,
            }
        },
        computed:{
            ...mapGetters([
                'msgTip',
                'localInfo',
                'loanInForm'
            ]),
            nameKey(){
                if(this.loanType == 'borrow') return '出借人'
                return '借款人'
            },
            nameKeyMe(){
                if(this.loanType == 'borrow') return '借款人'
                return '出借人'
            },
            isPublish(){
                return this.number == 'default'
            },
            userInfo(){
                return this.localInfo.userInfo
            },
            noAuth(){
                if(!this.userInfo.user) return false
                return this.userInfo.user.validState != 'OK'
            },
            amountToFen(){
                if(this.amount){
                    return (this.amount*100)
                }
            },
            amountRate(){
                if(this.amount && this.yearRate){   
                    return (this.amount*this.yearRate/10000).toFixed(2) + '元'
                }
            },
            amountFrom(){
                if(this.detail){
                    return toYuan(this.detail.lendAmountFrom)
                }
            },
            amountTo(){
                if(this.detail){
                    return toYuan(this.detail.lendAmountTo)
                }
            },
            amoutPlaceholder(){
                if(this.isPublish) return '请输入整数（元）'

                return `请输入${Number(this.amountFrom)} ~ ${Number(this.amountTo)}`
            },
            serviceFeeToFen(){
                if(this.serviceFee){

                    return Number(Math.round(this.serviceFee*100))
                }
            },
            calcDaysType(){
                if(this.payway == 'HBFX') return 'DAY'
                return 'PERIOD'
            },
            saveDays(){
                if(this.isPublish){
                    if(this.payway == 'HBFX'){
                        return this.days
                    }
                    else{
                        return this.periods
                    }
                }
                else{
                    if(this.detail){
                        if(this.detail.repayWay == 'HBFX'){
                            return this.days
                        }
                        else{
                            return this.periods
                        }  
                    }
                }
            },
            minDate(){
                if(!this.borrowDate) return ''
                return moment(new Date(this.borrowDate))
            },
            realDays(){
                let now = moment(new Date(this.borrowDate))
                let diff = moment(new Date(this.repayDate)) 
                let diffDays = Math.ceil(diff.diff(now,'days',true))
                return diffDays || ''
            },
            canCalc(){
                // publish
                if(this.isPublish){
                    if(!this.amount) return false
                    if(!this.realDays) return false
                    if(!this.serviceFee) return false

                    return true
                }

                // apply
                if(!this.amount) return false
                if(!this.realDays) return false

                return true
            },
            noCalc(){
                return _.isEmpty(this.calcObject)
            },
            isPublicBoolean(){
                if(this.isPublic == 0){
                    return false
                }
                return true
            }
        },
        methods:{
            // actions
            ...mapActions([
                'showLoading',
                'hideLoading',
                'setMsgTip',
                'setGoHome',
                'setLoanInApplyForm',
                'setLoanInPublishForm',
                'removeLoanInForm'
            ]),

            // filters
            timestampToDate(timestamp){
                if(!timestamp) return this.placeholder
                return moment(timestamp).format('YYYY-MM-DD')
            },

            // function
            setMax(){
                // console.log(Math.round(this.quota) / 100)
                let quotaToyuan = this.quota ? Math.round(this.quota) / 100 : 0
                if(this.amountToFen > this.quota){
                    this.amount = quotaToyuan
                }
            },
            caclServiceFeeRate(rate){
                let persent = rate / 100 + '%'
                return persent
            },
            payFinish(password){
                this.password = password
                this.showPayPassword = false
                this.publish()
            },
            saveForm(){
                if(!this.isPublish){
                    console.log(this.realDays)
                    this.setLoanInApplyForm({
                        amount:this.amount,
                        days:this.saveDays,
                        payway:this.detail.repayWay,
                    })
                }
                else{
                    this.setLoanInPublishForm({
                        amount:this.amount,
                        days:this.saveDays,
                        serviceFee:this.serviceFee,
                        payway:this.payway,
                        yearRate:this.yearRate,
                        isPublic:this.isPublic,
                    })
                }
            },
            goRouter(name){
                this.$router.push({
                    name:name
                })
            },
            goUse(){
                this.saveForm()
                this.$router.push({
                    name:'loan-in-want-use'
                })
            },
            goSuccess(no){
                this.removeLoanInForm()
                this.$router.replace({
                    name:'loan-in-success',
                    params:{
                        no:no
                    }
                })
            },
            goPay(){
                this.payStatus = true
                console.log(1)
            },
            goDetail(number){
                this.$router.push({
                    name:'loan-IOU-detail',
                    params:{
                        number:number,
                    }
                })
            },
            calc(){
                if(!this.canCalc) return
                this.loading_calc = true
                if(!this.isPublish){
                    loanInApi.calc({
                        borrowAmount:this.amountToFen,
                        repayWay:this.detail.repayWay,
                        borrowDays:this.realDays,
                        yearRate:this.detail.yearRate,
                        daysType:this.detail.daysType,
                        serviceFee:this.detail.serviceFee,
                        serviceFeeRate:this.detail.serviceFeeRate,
                    })
                    .then(result=>{
                        this.calcObject = result
                        this.loading_calc = false
                    })
                    .catch(error=>{
                        console.error(error)
                        this.loading_calc = false
                    })
                }
                else{
                    loanInApi.calc({
                        borrowAmount:this.amountToFen,
                        repayWay:this.payway,
                        borrowDays:this.realDays,
                        yearRate:this.yearRate,
                        daysType:this.calcDaysType,
                        serviceFee:this.serviceFeeToFen,
                    })
                    .then(result=>{
                        this.calcObject = result
                        this.loading_calc = false
                    })
                    .catch(error=>{
                        console.error(error)
                        this.loading_calc = false
                    })
                }
            },
            serviceFeeChange(){
                let maxServiceFee = Number((this.amount * 0.12).toFixed(2))
                if(!this.amount){
                    this.setMsgTip({
                        text:'请先输入借款金额',
                        type:'warn'
                    })
                    return
                }
                if(this.amount < 100){
                    this.setMsgTip({
                        text:'借款金额不能小于100元',
                        type:'warn'
                    })
                    return
                }
                if(this.serviceFee && !rules.number(+this.serviceFee)){
                    this.setMsgTip({
                        text:'服务费必须为整数',
                        type:'warn'
                    })
                    this.serviceFee = ''
                    return
                }
                if(+this.serviceFee > maxServiceFee){
                    this.setMsgTip({
                        text:`服务费不能超过${maxServiceFee}元`,
                        type:'warn'
                    })
                    return
                }
                this.calc()

            },
            confirm(){
                if(!this.userInfo.user){
                    this.showLogin = true
                    return
                }
                if(this.userInfo.user && this.userInfo.user.validState != 'OK'){
                    this.setMsgTip({
                        text:'请先实名认证',
                        type:'warn',
                    })
                    this.$router.push({
                        name:'user-bind-card-verified',
                        query:{
                            action:'back'
                        }
                    })
                    return false
                }
                let params = {
                    userProperty:this.loanType,
                    otherUserName:this.name,
                    borrowAmount:this.amountToFen,
                    borrowTimeStr:this.borrowDate || '',
                    repayTimeStr:this.repayDate,
                    yearRate:this.yearRate,
                    borrowUsage:this.usage
                }
                if(!LoanIOUAddValidation(params)) return
                if(this.realDays < 0){
                    this.setMsgTip({
                        text:'还款日期不能小于借款日期',
                        type:'warn'
                    })
                    return
                }
                this.publish()
            },
            publish(){
                this.showLoading()

                let data = {
                    tradePassword:this.password,
                    userProperty:this.loanType,
                    otherUserName:this.name,
                    borrowAmount:this.amountToFen,
                    borrowTimeStr:this.borrowDate || '',
                    repayTimeStr:this.repayDate,
                    yearRate:this.yearRate,
                    borrowUsage:this.usage
                }

                receiptApi.createReceipt(data)
                .then(result=>{
                    this.hideLoading()
                    this.goDetail(result.receiptNo)
                })
                .catch(error=>{
                    console.error(error)
                    this.hideLoading()
                })
            },
            getQuota(){
                this.showLoading()
                return userApi.quota()
                .then(result=>{
                    this.hideLoading()
                    this.quota = result.usableQuota
                    setTimeout(()=>{
                        this.showTips = true
                    },300)
                })
                .catch(error=> {
                    console.error(error);
                    this.hideLoading()
                    setTimeout(()=>{
                        this.showTips = true
                    },300)
                });
            },
            getUsage(num){
                loanInApi.usage()
                .then(result=>{
                    let arr = []
                    _.each(result,(value,index)=>{
                        arr.push({
                            value:value.name,
                            display:value.name
                        })
                    })
                    this.usageList = arr
                })
                .catch(error => {
                    console.error(error)
                })
            },
        },
        created(){
            if(!this.userInfo.user){
                this.showLogin = true
            }
            this.setGoHome(false)
            this.getUsage()
            this.getQuota()
        }
    }
</script>

<style lang="scss">
    @import "../sass/variables";
    @import "../sass/extends";
    @import "../sass/mixins";
    .loan-iou-add{
        // transform:translate3d(0,0,0);
        .wrapper{
            padding-bottom: 100px;
        }
        .amountRate{

        }
        .explain{
            @extend %font-caption;
            padding:8px 24px 0 24px;
            color:$importColor;
        }
        .money-info{
            margin-top:16px;
            position: relative;
        }
        .money-info__header{
            display: flex;
        }
        .money-info__title{
            @extend %font-body1;
            color:$importColor;
            padding-bottom: 8px;
            margin-bottom: 8px;
            border-bottom:1px solid $sectionColor;
        }
        .money-info__box{
            width: 100%;
            flex:1;
            position: relative;
            &:nth-of-type(2n){
                margin-left:24px;
            }
        }
        .money-info__item{
            @extend %font-caption;
            padding-top: 4px;
            display: flex;
            justify-content:space-between;
            &.fade{
                opacity:0;
            }
            &.today{
                color:$grayLight;
            }
        }
        .money-info__number{
            @extend %font-subhead;
            color:$orange;
            padding-top: 4px;
            text-align:right
        }
        .plan{
            padding-top: 16px;
        }
        .agreement{
            padding:16px;
        }
        .agreement__text{
            @extend %font-body1;
            font-weight:normal;
            display: block;
            color:$importColor;
        }
        .tips{
            @extend %font-caption;
            color:rgba(#000,.26);
            padding:0 16px 0 16px;
            line-height: 20px;
        }
        .have-two-item{
            p{
                @extend %font-subhead;
                padding-left: 8px;
            }
        }
        .year-rate{
            padding-left: 7px!important;
        }
        .real-days{
            position: absolute;
            top: 50%;
            transform:translate(0, -50%);
            right: 145px;
            @extend %font-subhead;
        }
    }

</style>
